package com.steria.workshop.android.yrapp;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.steria.workshop.android.yrapp.lib.model.WeatherData;
import com.steria.workshop.android.yrapp.lib.model.WeatherPeriod;
import com.steria.workshop.android.yrapp.lib.saxparser.YrSaxParser;

public class DailyWeatherActivity extends Activity {

	private ListView dailyListView;
	private List<WeatherPeriod> periods;
	private WeatherData weatherData;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		dailyListView = (ListView) findViewById(R.id.daily_list_view);
		dailyListView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				Intent i = new Intent(DailyWeatherActivity.this, WeatherDetailActivity.class);
				i.putExtras(weatherData.getWeatherPoint(periods.get(arg2).getFrom()).getBundle());
				DailyWeatherActivity.this.startActivity(i);
			}
		});

		periods = new ArrayList<WeatherPeriod>();
		ArrayAdapter<WeatherPeriod> dailyListAdapter = new ArrayAdapter<WeatherPeriod>(this,
				android.R.layout.simple_list_item_1, periods);
		dailyListView.setAdapter(dailyListAdapter);

		update();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		getMenuInflater().inflate(R.menu.main_menu, menu);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.main_menu_update:
			update();
			break;
		case R.id.main_menu_exit:
			this.finish();

			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void update() {
		double lat = Math.random() * 10;
		double lon = Math.random() * 10;
		new WeatherDataRetreiver().execute("http://api.yr.no/weatherapi/locationforecast/1.8/?lat=" + lat + ";lon="
				+ lon);
	}

	private class WeatherDataRetreiver extends AsyncTask<String, Integer, WeatherData> {

		@Override
		protected WeatherData doInBackground(String... arg) {
			YrSaxParser yrSaxParser = new YrSaxParser();
			return yrSaxParser.parse(arg[0]);
		}

		@Override
		protected void onPostExecute(WeatherData result) {
			periods.clear();
			weatherData = result;
			periods.addAll(result.getWeatherPeriods());
			((ArrayAdapter<WeatherPeriod>) dailyListView.getAdapter()).notifyDataSetChanged();
		}
	}
}